//
//  GMNoteVC.m
//  Teecloud
//
//  Created by 小熊 on 2018/10/18.
//  Copyright © 2018年 小志. All rights reserved.
//

#import "GMNoteVC.h"
#import "GMNoteModel.h"
#import "GMNoteCell.h"
#import "GMPopGMNoteVC.h"
#import "GMVoiceListModel.h"
@interface GMNoteVC ()<UITableViewDataSource,UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tabView;
@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, copy) NSString *curentTime;
@property (nonatomic, assign) NSInteger page;
@end

@implementation GMNoteVC
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"用户笔记";
    self.page = 0;
    [self.tabView registerNib:[UINib nibWithNibName:@"GMNoteCell" bundle:nil] forCellReuseIdentifier:@"GMNoteCell"];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getNoteData) name:@"updataNote" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getCurrentTime:) name:@"postTime" object:nil];
    self.tabView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(getNoteData)];
    self.tabView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(getMoreNoteData)];
    [self.tabView.mj_header beginRefreshing];
}
-(void)getCurrentTime:(NSNotification *)noti{
    NSDictionary *dict =[noti object];
    self.curentTime = dict[@"curentTime"];
}
- (void)getNoteData{
    self.page =0;
    NSDictionary *dict= @{@"from":FROM_IOS,
                          @"busiOrgId":[XGMArchiverTools cacheForKey:BUSIORGID],
                          @"loginFinger":[XGMArchiverTools cacheForKey:USER_identifierNumber],
                          @"userId":[XGMArchiverTools cacheForKey:USER_UserId],
                          @"resId":self.resId,
                          @"pageIndex":@(self.page),
                          @"pageSize":@(10)
                          };

    [HJNetwork HTTPWithMethod:HJRequestMethodPOST url:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=GetResNoteList&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [self.tabView.mj_header endRefreshing];
        [self.tabView.mj_footer endRefreshing];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                NSArray *arr = [GMNoteModel mj_objectArrayWithKeyValuesArray:[responseObject objectForKey:RESULT_NAME_Data]];
                [self.dataArr removeAllObjects];
                [self.dataArr addObjectsFromArray:arr];
                if (self.dataArr.count == 0) {
                    [self.tabView setupEmptyDataText:@"暂无数据" secoundText:@"" buttonTit:@"" verticalOffset:0 emptyImage:NODATAIMG tapBlock:^{
                        
                    } butClick:^{
                        
                    }];
                }
                [self.tabView reloadData];
            }
        }else{
            [MBProgressHUD showErrorOrSuc:@"请求出错" toView:self.view];
        }
    }];
}
- (void)getMoreNoteData{
    self.page++;
    NSDictionary *dict= @{@"from":FROM_IOS,
                          @"busiOrgId":[XGMArchiverTools cacheForKey:BUSIORGID],
                          @"loginFinger":[XGMArchiverTools cacheForKey:USER_identifierNumber],
                          @"userId":[XGMArchiverTools cacheForKey:USER_UserId],
                          @"resId":self.resId,
                          @"pageIndex":@(self.page),
                          @"pageSize":@(10)
                          };
    
    [HJNetwork HTTPWithMethod:HJRequestMethodPOST url:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=GetResNoteList&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                NSArray *arr = [GMNoteModel mj_objectArrayWithKeyValuesArray:[responseObject objectForKey:RESULT_NAME_Data]];
                if (arr.count >0) {
                    [self.tabView.mj_footer endRefreshing];
                    [self.tabView.mj_header endRefreshing];
                    [self.dataArr addObjectsFromArray:arr];
                    [self.tabView reloadData];
                }else{
                    self.tabView.mj_footer.state = MJRefreshStateNoMoreData;
                }
            }
        }else{
            [MBProgressHUD showErrorOrSuc:@"请求出错" toView:self.view];
        }
    }];
}
-(NSMutableArray *)dataArr{
    if (!_dataArr) {
        _dataArr = [[NSMutableArray alloc] init];
    }
    return _dataArr;
}

- (UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    GMNoteCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GMNoteCell" forIndexPath:indexPath];
    GMNoteModel *model = self.dataArr[indexPath.row];
    cell.model = model;
    cell.baseVC = self;
    kWeakObject(self)
    cell.playTap = ^{
        NSDictionary *dict = @{@"playTime":model.Position};
        [[NSNotificationCenter defaultCenter] postNotificationName:@"playWithTheTime" object:dict];
    };
    cell.hasReadBlock = ^(NSInteger index, NSString *voiceID){
        NSDictionary *dict= @{@"from":FROM_IOS,
                              @"busiOrgId":[XGMArchiverTools cacheForKey:BUSIORGID],
                              @"loginFinger":[XGMArchiverTools cacheForKey:USER_identifierNumber],
                              @"userId":[XGMArchiverTools cacheForKey:USER_UserId],
                              @"voiceId":voiceID,
                              };

        [HJNetwork HTTPWithMethod:HJRequestMethodPOST url:[NSString stringWithFormat:@"v30.teecloud.cn/ajax-api.ashx?$c=TeeyunApp&$m=PostVoiceReadStatus&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
          
            if (!error) {
                if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                    for (NSInteger i=0; i<model.VoiceList.count; i++) {
                        GMVoiceListModel *temModel = model.VoiceList[i];
                        if (i == index) {
                            temModel.IsReaded =YES;
                        }
                    }
                    [weakself.tabView reloadData];
                }else{
                    [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:weakself.view];
                }
            }else{
                [MBProgressHUD showErrorOrSuc:@"请求出错" toView:weakself.view];
            }
        }];
    };
    return cell;
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    self.tabView.mj_footer.hidden = self.dataArr.count == 0;
    return self.dataArr.count;
}
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 280;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    GMNoteModel *model = self.dataArr[indexPath.row];
    return model.cellHight;
}
- (IBAction)sumbitNote:(id)sender {
    //发送通知，暂停播放
    [[NSNotificationCenter defaultCenter] postNotificationName:@"comentPause" object:nil];
    GMPopGMNoteVC *note = [[GMPopGMNoteVC alloc] init];
    note.resId = self.resId;
    note.timeLenth = self.curentTime;
    [self.navigationController presentSemiViewController:note withOptions:@{
                                                                                KNSemiModalOptionKeys.pushParentBack    : @(NO),
                                                                                KNSemiModalOptionKeys.animationDuration : @(0.5),
                                                                                KNSemiModalOptionKeys.shadowOpacity     : @(0.3)
                                                                                }];
}
-(void)dealloc{
    /**移除通知*/
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
